package com.sites.common.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.io.FileUtil;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log4jLog;
import com.jfinal.upload.UploadFile;
import com.sites.common.SiteInfo;
import com.sites.common.model.Files;

/**
 * 文件服务层
 * 
 * @author zyg
 * 2020年2月6日 下午3:44:04
 */
public class FileService {

	private Log4jLog log = Log4jLog.getLog(FileService.class);
	private Files dao = new Files().dao();
	
	/**
	 * 上传文件
	 * @param uploadFile	jfinal获取的文件实体
	 * @param type			文件类型
	 * @return
	 */
	public Ret upload(UploadFile uploadFile, String type){
		String filePath = "";//文件实际存储位置
		String savePath = "";//数据库里保存的路径
		
		String fileName = uploadFile.getFileName();
		String originalFileName = uploadFile.getOriginalFileName();
		String contentType = uploadFile.getContentType();
		File file = uploadFile.getFile();
		Date date = new Date();
		String now = DateKit.toStr(date, "YYYYMM");
		if(SiteInfo.uploadPath.endsWith(File.separator)){
			filePath = SiteInfo.uploadPath + now + File.separator;
		} else {
			filePath = SiteInfo.uploadPath + File.separator + now + File.separator;
		}
		String suffix = fileName.substring(fileName.lastIndexOf("."));//获取原始文件后缀
		fileName = StrKit.getRandomUUID()+suffix;//自定义一个唯一标识码做文件名
		File newFile = new File(filePath+File.separator+fileName);
		
		/*
		 * 切换文件目录
		 * 优先使用file.renameTo，当其失效时使用FileUtil.copy
		 */
		boolean flag = file.renameTo(newFile);
		if(!flag){
			log.info("使用FileUtil.copy()切换目录");
			FileUtil.copy(file, newFile, false);
			FileUtil.del(file);
		}
		
		savePath = File.separator + now + File.separator + fileName;
		
		//文件信息保存到数据库
		Files files = new Files();
		files.setType(type);
		files.setName(fileName);
		files.setOriginalName(originalFileName);
		files.setContentType(contentType);
		files.setPath(savePath);
		files.setCreateTime(date);
		files.save();
		
		Ret ret = Ret.ok(SiteInfo.msgKey, "上传成功");
		ret.set("fileId", files.getId());
		ret.set("fileName", originalFileName);
		ret.set("savePath", savePath);
		return ret;
	}
	
	/**
	 * 富文本编辑器使用的图片上传方法
	 * 
	 * @param uploadFile
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Ret uploadImg4Editor(UploadFile uploadFile, String type){
		Ret temp = upload(uploadFile, type);
		Ret ret = Ret.create();
		if(temp.isOk()){
			ret.set("errno", 0);
			ArrayList<String> data = new ArrayList<String>();
			data.add(temp.getStr("savePath"));
			ret.put("data", data);
		}
		return ret;
	}
	
	/**
	 * 使用layer相册层预览图片使用
	 * <br/>需要返回固定格式的数据
	 * {
	 *		"title": "", //相册标题
	 *		"id": 123, //相册id
	 *		"start": 0, //初始显示的图片序号，默认0
	 *		"data": [   //相册包含的图片，数组格式
	 *			{
	 *				"alt": "图片名",
	 *				"pid": 666, //图片id
	 *				"src": "", //原图地址
	 *				"thumb": "" //缩略图地址
	 *			}
	 *		]
	 *	}
	 *
	 * @param id
	 * @return
	 */
	public Ret getImg(int id){
		/**
		 * 
		 */
		Ret ret = Ret.create();
		Files img = getById(id);
		ret.set("title", "");
		ret.set("id", id);
		Kv imgKv = Kv.create();
		imgKv.set("alt", img.getOriginalName());
		imgKv.set("pid", img.getId());
		String path = img.getPath();
		imgKv.set("src", path);
		imgKv.set("thumb", "");
		List<Kv> imgList = new ArrayList<Kv>();
		imgList.add(imgKv);
		ret.set("data", imgList);
		return ret;
	}
	
	public Files getById(int id){
		return dao.findById(id);
	}
	
	public List<Files> getByIds(String ids){
		List<Files> files = new ArrayList<Files>();
		if(StrKit.isBlank(ids)){
			return files;
		}
		
		String[] idsStrings = ids.split(",");
		int id;
		for(int i=0,j=idsStrings.length; i<j; i++){
			id = Integer.parseInt(idsStrings[i]);
			files.add(getById(id));
		}
		return files;
	}
}
